<?php
/**
 * 接口配置
 * Enter description here ...
 * @author jin
 *
 */
class ControllerMessageWeekSituation extends Controller {
	private $error = array();

	protected function init(){
		$this->load_language('message/week_situation');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('message/week_situation');
	}

	public function index() {
		$this->init();
		$this->getList();
	}
	
	public function insert() {
		$this->init();

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_message_week_situation->addWeekSituation($this->request->post);
			$this->redirectToNews();
		}

		$this->getForm();
	}

	public function update() {
		$this->init();

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_message_week_situation->editWeekSituation($this->request->get['week_situation_id'], $this->request->post);
			$this->redirectToNews();
		}

		$this->getForm();
	}

	public function delete() {
		$this->init();

		if (isset($this->request->post['selected']) && $this->validateDelete()) {
			foreach ($this->request->post['selected'] as $postion_id) {
				$this->model_message_week_situation->deleteWeekSituation($postion_id);
			}

			$this->redirectToList();
		}

		$this->getList();
	}
	 
	
	private function getList(){
		
		$this->load->model('tool/image');
		
		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$data = array(
			'start' => ($page - 1) * $this->config->get('config_admin_limit'),
			'limit' => $this->config->get('config_admin_limit')
		);


		$this->data['newss'] = array();
		$total = $this->model_message_week_situation->getTotalWeekSituations();
		$results = $this->model_message_week_situation->getWeekSituations();
		foreach ($results as $news_info) {
			$action = array();

			$action[] = array(
				'text' => $this->language->get('text_edit'),
				'type' => "edit",
				'href' => $this->url->link('message/week_situation/update', 'token=' . $this->session->data['token'] . '&week_situation_id=' . $news_info['week_situation_id'] , 'SSL')
			);
			
			/*
			$action[] = array(
				'text' => $this->language->get('推送'),
				'type' => "push",
				'href' => $this->url->link('message/week_situation/push', 'token=' . $this->session->data['token'] . '&week_situation_id=' . $news_info['week_situation_id'] , 'SSL')
			);
			*/

			$this->data['newss'][] = array(
				'week_situation_id'=>$news_info['week_situation_id'],
				'name'=>$news_info['name'],
				'type'=>$news_info['type']?"图文":"文本",
				'status'     => ($news_info['status'] ? $this->language->get('text_enabled') : $this->language->get('text_disabled')),
				'actions'     => $action,
				'selected'   => isset($this->request->post['selected']) && in_array($news_info['week_situation_id'], $this->request->post['selected']),
			);
		}

		$url = "";

		if(isset($this->request->get['week_situation_id']))
		{
			$url = "&week_situation_id="+$this->request->get['week_situation_id'];
		}


		$this->data['insert'] = $this->url->link('message/week_situation/insert', 'token=' . $this->session->data['token'], 'SSL');
		$this->data['delete'] = $this->url->link('message/week_situation/delete', 'token=' . $this->session->data['token'].$url, 'SSL');
		
		$this->data['token'] = $this->session->data['token'];
		
		$pagination = new Pagination();
		$pagination->total = $total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_admin_limit');
		$pagination->text = $this->language->get('text_pagination');
		$pagination->url = $this->url->link('message/week_situation', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');
		$this->data['pagination'] = $pagination->render();
		
		
		$this->template = 'message/week_situation_list.tpl';
		$this->children = array(
			'common/header',
			'common/footer'
		);
		$this->response->setOutput($this->render());
	}
	
	
	public function push(){
		
		$this->init();
		$this->load->model('config/weixin');
		
		if($this->request->get['week_situation_id']){
			$week_siteuation_id = $this->request->get['week_situation_id'];
		}else{
			$week_siteuation_id = 0;
		}
		$policeSituationInfos = $this->model_message_week_situation->getPoliceSituations($week_siteuation_id);
		
		$articles = array();
		foreach ($policeSituationInfos as $index => $policeSituationInfo) {
			$image = "/home/vol8_5/byethost22.com/b22_15294199/htdocs/weixin_php/".$policeSituationInfo['ab_pic_url'];
			$token = $this->model_config_weixin->getAccessToken(APP,APK);
		      	//上传图片
			$param = array(
				'media'=>new CURLFile ("E:/workspace/opencart-workspace/mp_server/image/cache/data/car_bz-100x100.jpg"),
				//'media'=>new CURLFile ($image),
				  //'media'=>"@".$image
			);
	      	$picTheInfo = json_decode($this->upload_pic("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=".$token."&type=image",$param));
	      	
	        $thumb_media_id = $picTheInfo->media_id;
	      	
	        $title = urlencode($policeSituationInfo['title']);
			$title =str_replace("&quot;","\"", $title);
			$title = str_replace("'","", $title);
	        
			$content = urlencode($policeSituationInfo['title']);
			$content =str_replace("&quot;","\"", $content);
			$content = str_replace("'","", $content);

			$summary = urlencode($policeSituationInfo['summary']);
			$summary =str_replace("&quot;","\"", $summary);
			$summary = str_replace("'","", $summary);
			
	      	//上传图文，回去media_id
			$articles[] = array(
				 "thumb_media_id"=>$thumb_media_id,
	             "author"=>"胥江派出所",
				 "title"=>$title,
				 "content_source_url"=>HTTP_CATALOG.$policeSituationInfo['url'],
				 "content"=>$content,
				 "digest"=>$summary,
	             "show_cover_pic"=>$index?"1":"0",
			);
			
		}
				
		$infos = array("articles"=>$articles);
		$arss = urldecode ( Json::encode($infos) );
		$aricleString = $arss;
		$aricleString =str_replace("&quot;","\"", $aricleString);
		$aricleString = str_replace("'","", $aricleString);
		$ar_url = 'https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token='.$token;
		$articleInfo = weiUtil::dataPost($aricleString, $ar_url);
		$article_info = json_decode($articleInfo);
		$media_id = $article_info->media_id;
		
		//发送推送图文消息
		$touser = array();
		//oZvkltzM1UkSyXHR7aaQj9KyYF_A
		$touser[] = 'oZvklt3Qv3W1-VKTr1zmoXMPARh4';
		$picInfo = array(
			"touser"=>$touser,
			"mpnews"=>array("media_id"=>$media_id),
			"msgtype"=>"mpnews"
		);
		$each_ar_url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=".$token;
		$eachArss = urldecode ( Json::encode($picInfo) );
		$eachAricleString = $eachArss;
		$eachAricleString =str_replace("&quot;","\"", $eachAricleString);
		$eachAricleString = str_replace("'","", $eachAricleString);
	   // $result = weiUtil::dataPost($eachAricleString, $each_ar_url);
	    
		$returnInfo = json_decode($result);
		
		$this->load->library('json');
		$json = array();
		
		if(!$returnInfo->errcode){
			$json ['status'] = "success";
		}else{
			$json ['status'] = "fail";
		}
		
		$this->response->setOutput(Json::encode($json));
		
	}
	 
	public function menu() {
		$this->load->model('config/menu');
		$this->load_language('message/news');
		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$data = array(
			'start' => ($page - 1) * $this->config->get('config_admin_limit'),
			'limit' => $this->config->get('config_admin_limit')
		);


		$this->data['menuRoutes'] = array();

		$results = $this->model_config_menu->getAllMenuRoutes();
		foreach ($results as $result) {
			$action = array();

			$action[] = array(
				'text' => $this->language->get('text_set'),
				'type' => "edit",
				'href' => $this->url->link('message/news/set', 'token=' . $this->session->data['token'] . '&menu_route_id=' . $result['menu_route_id'] , 'SSL')
			);


			$this->data['menuRoutes'][] = array(
				'menu_route_id'    => $result['menu_route_id'],
      			'display_name'    => $result['display_name'],
      			'menu_url'    => $result['menu_url'],
				'actions'     => $action,
      			'selected'   => isset($this->request->post['selected']) && in_array($result['menu_route_id'], $this->request->post['selected']),
			);
		}

		$url = "";

		if(isset($this->request->get['menu_route_id']))
		{
			$url = "&menu_route_id="+$this->request->get['menu_route_id'];
		}


		$this->data['insert'] = $this->url->link('message/news/insert', 'token=' . $this->session->data['token'], 'SSL');
		$this->data['delete'] = $this->url->link('message/news/delete', 'token=' . $this->session->data['token'].$url, 'SSL');
		
		$this->data['token'] = $this->session->data['token'];
		
		$this->template = 'message/menu_news_list.tpl';
		$this->children = array(
			'common/header',
			'common/footer'
		);
		$this->response->setOutput($this->render());
	}
	
	
	public function set(){
		$this->load->model('message/news');
		$this->load_language('message/news');
		
		
		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_message_news->editNewsToMenu($this->request->get['menu_route_id'],$this->request->post);
			$this->redirectToList();
		}
		
		if (isset($this->error['title'])) {
			$this->data['error_title'] = $this->error['title'];
		} else {
			$this->data['error_title'] = '';
		}

		if (isset($this->error['error_date'])) {
			$this->data['error_date'] = $this->error['error_date'];
		} else {
			$this->data['error_date'] = '';
		}

		if (isset($this->error['warning'])) {
			$this->data['error_warning'] = $this->error['warning'];
		} else {
			$this->data['error_warning'] = '';
		}

		$url=$this->getUrlParameters();

		$this->data['breadcrumbs'] = array();

		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
      		'separator' => false
		);

		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('heading_title'),
			'href'      => $this->url->link('message/news', 'token=' . $this->session->data['token'] , 'SSL'),
      		'separator' => ' :: '
      		);

		
      		if(isset( $this->request->get['menu_route_id'])){
	      		$this->data['action'] = HTTPS_SERVER . 'index.php?route=message/news/set&token=' . $this->session->data['token'] . '&menu_route_id=' . $this->request->get['menu_route_id'] . $url;
      		}else{
      			$this->data['action'] = HTTPS_SERVER . 'index.php?route=message/news/set&token=' . $this->session->data['token']  . $url;
      		}
      		
      		$this->data['cancel'] = HTTPS_SERVER . 'index.php?route=message/news/menu&token=' . $this->session->data['token'] . $url;

      		$this->data['token'] = $this->session->data['token'];

      		if (isset($this->request->get['menu_route_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
      			$news_info = $this->model_message_news->getNewsByRouteId($this->request->get['menu_route_id']);
	      		$this->data['newsInfo'] = $news_info;
      		}
			
      		
      		/*
			if (isset($this->request->post['articles'])) {
				$this->data['articles'] = $this->request->post['articles'];
			} elseif (!empty($route_info)) {
				$this->data['articles'] = array();
				$data = array(
					'filter_news_id'=>$route_info['news_id'],
				);
				$this->load->model('message/article');
				$articles = $this->model_message_article->getRelatedArticles($data);
				if($articles){
					foreach ($articles as $article) {
						$abPic = "";
						if ($article['pic_url'] && file_exists(DIR_IMAGE . $article['pic_url'])) {
							$abPic = $this->model_tool_image->resize($article['pic_url'], 100, 100);
						} else {
							$abPic = $this->model_tool_image->resize('no_image.jpg', 100, 100);
						}
						$this->data['articles'][] = array(
							'news_article_id'=>$article['news_article_id'],
							'title'=>$article['title'],
							'description'=>$article['description'],
							'pic_url'=>$article['pic_url'],
							'abPic' =>$abPic,
							'url' =>$article['url'],
							'url_type' =>$article['url_type'],
						);
					}
				}
			} else {
				$this->data['articles'] = array();
			}
			*/
			
			
      		$this->data['text_browse'] = $this->language->get('text_browse');
      		$this->data['text_clear'] = $this->language->get('text_clear');
      		$this->template = 'message/menu_news_form.tpl';
			$this->children = array(
				'common/header',
				'common/footer'
			);
			$this->response->setOutput($this->render());
		
	}
	
	
	private function getForm() {
		
		
		if (isset($this->error['title'])) {
			$this->data['error_title'] = $this->error['title'];
		} else {
			$this->data['error_title'] = '';
		}

		if (isset($this->error['error_date'])) {
			$this->data['error_date'] = $this->error['error_date'];
		} else {
			$this->data['error_date'] = '';
		}

		if (isset($this->error['warning'])) {
			$this->data['error_warning'] = $this->error['warning'];
		} else {
			$this->data['error_warning'] = '';
		}

		$url=$this->getUrlParameters();

		$this->data['breadcrumbs'] = array();

		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
      		'separator' => false
		);

		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('heading_title'),
			'href'      => $this->url->link('message/week_situation', 'token=' . $this->session->data['token'] , 'SSL'),
      		'separator' => ' :: '
      		);

		
      		if(isset( $this->request->get['week_situation_id'])){
	      		$this->data['action'] = HTTPS_SERVER . 'index.php?route=message/week_situation/update&token=' . $this->session->data['token'] . '&week_situation_id=' . $this->request->get['week_situation_id'] . $url;
      		}else{
      			$this->data['action'] = HTTPS_SERVER . 'index.php?route=message/week_situation/insert&token=' . $this->session->data['token']  . $url;
      		}
      		
      		$this->data['cancel'] = HTTPS_SERVER . 'index.php?route=message/week_situation&token=' . $this->session->data['token'] . $url;

      		$this->data['token'] = $this->session->data['token'];

      		if (isset($this->request->get['week_situation_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
      			$news_info = $this->model_message_week_situation->getWeekSituation($this->request->get['week_situation_id']);
      		}
			if (isset($this->request->post['create_time'])) {
				$this->data['create_time'] = $this->request->post['create_time'];
			} elseif (!empty($news_info)) {
				$this->data['create_time'] = $news_info['create_time'];
			} else {
				$this->data['create_time'] = '';
			}
			
			if (isset($this->request->post['type'])) {
				$this->data['type'] = $this->request->post['type'];
			} elseif (!empty($news_info)) {
				$this->data['type'] = $news_info['type'];
			} else {
				$this->data['type'] = '';
			}
			
			if (isset($this->request->post['status'])) {
				$this->data['status'] = $this->request->post['status'];
			} elseif (!empty($news_info)) {
				$this->data['status'] = $news_info['status'];
			} else {
				$this->data['status'] = '';
			}
			
			if (isset($this->request->post['name'])) {
				$this->data['name'] = $this->request->post['name'];
			} elseif (!empty($news_info)) {
				$this->data['name'] = $news_info['name'];
			} else {
				$this->data['name'] = '';
			}
			
			if (isset($this->request->post['value'])) {
				$this->data['value'] = $this->request->post['value'];
			} elseif (!empty($news_info)) {
				$this->data['value'] = $news_info['value'];
			} else {
				$this->data['value'] = '';
			}
			$this->load->model('tool/image');
			$this->data['no_image'] = $this->model_tool_image->resize('no_image.jpg', 100, 100);
			
			if (isset($this->request->post['articles'])) {
				$this->data['articles'] = $this->request->post['articles'];
			} elseif (!empty($news_info)) {
				$this->data['articles'] = array();
				$data = array(
					'filter_week_situation_id'=>$news_info['week_situation_id'],
				);
				
				$this->load->model('message/police_situation');
				$articles = $this->model_message_police_situation->getRelatedArticles($data);
				//print_r($articles);
				if($articles){
					foreach ($articles as $article) {
						$abPic = "";
						if ($article['pic_url'] && file_exists(DIR_IMAGE . $article['pic_url'])) {
							$abPic = $this->model_tool_image->resize($article['pic_url'], 100, 100);
						} else {
							$abPic = $this->model_tool_image->resize('no_image.jpg', 100, 100);
						}
						$this->data['articles'][] = array(
							'police_situation_id'=>$article['police_situation_id'],
							'title'=>$article['title'],
							'description'=>$article['description'],
							'pic_url'=>$article['pic_url'],
							'abPic' =>$abPic,
							'url' =>$article['url'],
							'url_type' =>$article['url_type'],
						);
					}
				}
				
			} else {
				$this->data['articles'] = array();
			}
			
			
			
      		$this->data['text_browse'] = $this->language->get('text_browse');
      		$this->data['text_clear'] = $this->language->get('text_clear');
      		$this->template = 'message/week_situation_form.tpl';
			$this->children = array(
				'common/header',
				'common/footer'
			);
			$this->response->setOutput($this->render());
      		
	}
	
	
	public function example(){
		$this->template = 'config/config_position_example.tpl';
		$this->children = array(
			'common/header',
			'common/footer'
		);
		$this->response->setOutput($this->render());
	}

	private function validateForm() {
		/*
		if (!$this->user->hasPermission('modify', 'catalog/article')) {
			$this->error['warning'] = sprintf($this->language->get('error_permission'),$this->language->get('heading_title'));
		}

		foreach ($this->request->post['article'] as $language_id => $value) {
			if ((strlen(utf8_decode($value['title'])) < 1)) {
				$this->error['title'][$language_id] = $this->language->get('error_name');
			}
		}
		 */
		if (!$this->error) {
			return TRUE;
		} else {
			$this->error['warning'] = $this->language->get('error_required_data');
				
			return FALSE;
		}
	}

	private function validateDelete() {
		/*
		if (!$this->user->hasPermission('modify', 'catalog/article')) {
			$this->error['warning'] = sprintf($this->language->get('error_permission'),$this->language->get('heading_title'));
		}
*/
		if (!$this->error) {
			return TRUE;
		} else {
			return FALSE;
		}
	}


	private function redirectToNews(){
		$this->session->data['success'] = sprintf($this->language->get('text_success'),$this->language->get('heading_title'));

		$url=$this->getUrlParameters();

		$this->redirect(HTTPS_SERVER . 'index.php?route=message/week_situation&token=' . $this->session->data['token'] . $url);
	}
	
	private function redirectToList(){
		$this->session->data['success'] = sprintf($this->language->get('text_success'),$this->language->get('heading_title'));

		$url=$this->getUrlParameters();

		$this->redirect(HTTPS_SERVER . 'index.php?route=message/week_situation&token=' . $this->session->data['token'] . $url);
	}
	 
	private function getCommonUrlParameters(){
		$url = '';

		if (isset($this->request->get['filter_title'])) {
			$url .= '&filter_title=' . $this->request->get['filter_title'];
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}

		if (isset($this->request->get['filter_date_add'])) {
			$url .= '&filter_date_add=' . $this->request->get['filter_date_add'];
		}

		if (isset($this->request->get['filter_article_category_id'])) {
			$url .= '&filter_article_category_id=' . $this->request->get['filter_article_category_id'];
		}

		return $url;
	}
	 
	public function getUrlParameters(){
		$url = '';

		$url=$this->getCommonUrlParameters();

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		return $url;
	}
	
	
	
	public function autocomplete() {
		$json = array();

		if (isset($this->request->get['filter_name'])) {
			$this->load->model('message/news');

			$data = array(
				'filter_name' => $this->request->get['filter_name'],
				'start'       => 0,
				'limit'       => 100
			);

			$results = $this->model_message_news->getNewss($data);

			foreach ($results as $result) {
				$json[] = array(
					'news_id' => $result['news_id'], 
					'name'        => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8'))
				);
			}		
		}

		$sort_order = array();

		foreach ($json as $key => $value) {
			$sort_order[$key] = $value['name'];
		}

		array_multisort($sort_order, SORT_ASC, $json);

		$this->response->setOutput(json_encode($json));
	}		
	
/**
	 * 获取th id
	 */
	public function upload_pic($url, $data = null)
	{
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		if (!empty($data)){
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		
		$output = curl_exec($curl);
		curl_close($curl);
		return $output;
	}
	
public function curlPost($url, $params = NULL, $option = array()) {

		if (is_array($params) && !empty($params)) {

			$p = http_build_query($params);

		} else {

			$p = $params;

		}

		$ch = curl_init($url);

		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

		curl_setopt($ch, CURLOPT_POST, TRUE);

		curl_setopt($ch, CURLOPT_POSTFIELDS, $p);

		curl_setopt_array($ch, $option);

		$result = curl_exec($ch);

		curl_close($ch);

		return $result ? $result : false;

	}

}
?>